package api

import (
	"api/basic/config"
	"api/basic/pkg"
	"api/basic/proto/video"
	"api/handler/request"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"path/filepath"
	"time"
)

func VideoAdd(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	ext := filepath.Ext(file.Filename)
	if ext != ".mp4" && ext != ".jpg" {
		c.JSON(http.StatusBadGateway, gin.H{
			"code": 10001,
			"msg":  "类型不正确",
			"data": ext})
		return
	}
	if file.Size >= 150*1024*1024 {
		c.JSON(http.StatusBadGateway, gin.H{
			"code": 10001,
			"msg":  "视频过大",
			"data": ext})
		return
	}
	format := time.Now().Format("20060102150405")
	dst := "./basic/pkg/imagers/" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)
	aly := pkg.ALY(dst, format+ext)
	// Contact the server and print out its response.

	r, err := config.S.VideoAdd(c, &video.VideoAddReq{
		VideoString: aly,
		UserId:      1,
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r)
	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", r))
}

func UserList(c *gin.Context) {
	var data request.UserListReq
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusBadGateway, gin.H{
			"code": 10001,
			"msg":  "错误",
			"data": err.Error()})
		return
	}
	r, err := config.S.UserDetails(c, &video.UserDetailsReq{
		UserId: int32(data.Userid),
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "用户详情",
		"data": r})
}

func VideoList(c *gin.Context) {
	var data request.UserListReq
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusBadGateway, gin.H{
			"code": 10001,
			"msg":  "错误",
			"data": err.Error()})
		return
	}
	r, err := config.S.VideoList(c, &video.VideoListReq{
		UserId: int32(data.Userid),
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "视频列表",
		"data": r})
}
